<?php

namespace App\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Auth;
use App\Models\Site;
use CodeService;
use Exception;
use App\Notifications\CodeNotification;
use Illuminate\Contracts\Container\BindingResolutionException;
use Illuminate\Http\Response;
use Illuminate\Contracts\Routing\ResponseFactory;
use Illuminate\Validation\Rule;
use App\Models\User;

/**
 * 验证码发送
 * @package App\Api
 */
class CodeController extends Controller
{
    public function __construct()
    {
    }

    /**
     * 当前用户发送手机验证码
     * @return void
     */
    public function mobile()
    {
        try {
            CodeService::mobile(Auth::user()->mobile);
            return $this->message('短信发送成功');
        } catch (Exception $e) {
            return $this->error('发送失败，手机号错误或发送频繁');
        }
    }

    /**
     * 为不存在手机发送验证码
     * @return Response|ResponseFactory|array|void
     */
    public function mobileNoExist(Request $request)
    {
        $request->validate([
            'mobile' => ['required', Rule::unique('users', 'mobile')]
        ], [
            'mobile.required' => '手机号不能为空',
            'mobile.unique' => '手机已经被使用'
        ]);
        try {
            CodeService::mobile($request->mobile);
            return $this->message('短信发送成功');
        } catch (Exception $e) {
            return $this->error('发送失败，请检测手机格式' . $e->getMessage());
        }
    }

    /**
     * 邮件验证码
     * @param mixed $email
     * @return mixed
     * @throws BindingResolutionException
     */
    public function email()
    {
        try {
            CodeService::mobile(Auth::user()->email);
            return $this->message('邮箱验证码发送成功');
        } catch (Exception $e) {
            return $this->error('发送失败，请检测邮箱格式' . $e->getMessage());
        }
    }

    /**
     * 为不存在邮箱发送验证码
     * @return Response|ResponseFactory|array|void
     */
    public function emailNoExist(Request $request)
    {
        $request->validate([
            'email' => ['required', Rule::unique('users', 'email')],
            'captcha.content' => ['sometimes', 'required', 'captcha_api:' . request('captcha.key') . ',default']
        ], [
            'email.required' => '邮箱不能为空',
            'email.unique' => '邮箱已经被使用',
            'captcha.content.required' => '验证码不能为空',
            'captcha.content.captcha_api' => '验证码输入错误'
        ]);
        try {
            CodeService::email($request->email);
            return $this->message('邮箱验证码发送成功');
        } catch (Exception $e) {
            return $this->error('发送失败，请检测邮箱格式' . $e->getMessage());
        }
    }
}
